
var MyLinkedList = function () {
    this.head = null; // 链表头
    this.size = 0; // 链表长度
};

var Node = function (val) {
    this.val = val;
    this.next = null;
};


MyLinkedList.prototype.get = function (index) {
    if (index < 0 || index >= this.size) return -1;

    let cur = this.head;
    while (index) {
        cur = cur.next;
        index--
    }
    return cur.val
};


MyLinkedList.prototype.addAtHead = function (val) {
    let newNode = new Node(val)
    newNode.next = this.head;
    this.head = newNode
    this.size++
};


MyLinkedList.prototype.addAtTail = function (val) {
    let newNode = new Node(val)
    let cur = this.head
    if (!cur) this.head = newNode
    while (cur.next) {
        cur = cur.next;
    }
    cur.next = newNode
    this.size++
};


MyLinkedList.prototype.addAtIndex = function (index, val) {
    if (index < 0 || index > this.size) return -1;

    if (index === 0) {
        this.addAtHead(val);
    } else {
        const newNode = new Node(val);
        let cur = this.head;
        while (--index) {
            cur = cur.next;
        }
        newNode.next = cur.next;
        cur.next = newNode;
        this.size++;
    }
};


MyLinkedList.prototype.deleteAtIndex = function (index) {
    if (index < 0 || index >= this.size) return -1;

    if (index === 0) {
        this.head = this.head.next;
    } else {
        let cur = this.head;
        while (--index > 0) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
    }
    this.size--;
};

